<?php


namespace app\service;


use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class AmqpService
{
    private static function getRabbitMqObj()
    {
        $connection = new AMQPStreamConnection('192.168.152.135', 5672, 'admin', 'admin', 'my_vhost');

        return $connection;
    }

    public static function send(array $data)
    {
        addlog(['发送输入到rabbitmq', $data]);

        $connection = self::getRabbitMqObj();
        $channel = $connection->channel();


        $channel->queue_declare('crawler', false, false, false, false);


        $msg = new AMQPMessage(json_encode($data));
        $channel->basic_publish($msg, '', 'crawler');


        $channel->close();
        $connection->close();
    }

    public static function receive()
    {

        $connection = self::getRabbitMqObj();
        $channel = $connection->channel();

        $channel->queue_declare('crawler', false, false, false, false);

        addlog(' [*] Waiting for messages. To exit press CTRL+C');

        $callback = function ($msg) {

            $data = json_decode($msg->body,true);
            CrawlerService::start($data);
        };

        $channel->basic_consume('crawler', '', false, true, false, false, $callback);

        while (count($channel->callbacks)) {
            $channel->wait();
        }

        $channel->close();
        $connection->close();
    }
}